package gui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.UIManager;

import model.Constants;
import model.ProduccionBase;

import org.joda.time.DateTime;

import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jgoodies.looks.plastic.PlasticLookAndFeel;
import com.jgoodies.looks.plastic.theme.DesertBlue;
import com.toedter.calendar.JDateChooser;



public class PostresElyMainFrame extends JFrame implements ComponentListener, PropertyChangeListener, ActionListener {

		
		static final int WIDTH = 1000;
        static final int HEIGHT = 470;
        static final int MIN_WIDTH = 1000;
        static final int MIN_HEIGHT = 470;

		Container contentPane;
		JFrame parent;
		PudinesPanel current;
		Task task;
		ProgressMonitor progdialog;
		JProgressBar pbar;
		JTabbedPane tabbedPane;
		JDialog dialog;
		boolean ok;
		JDateChooser date;
		DateTime dia;
		ImageIcon redicon,greenicon;
		ArrayList<ArrayList<JTable>> allTables;

		public class tabbedPaneRunnable implements Runnable {

		    public void run() {
		    	setupTabbedPane();		    
		    }


		}
		
		class Task extends SwingWorker<Void, Void> {
			/*
			 * Main task. Executed in background thread.
			 */
			
			public synchronized Void doInBackground() {
				@SuppressWarnings("unused")
				int progress = 0;
				int progressMax = Constants.MAX_PROGRESS;
				// Initialize progress property.
				setProgress(0);
				
				 Thread t = (new Thread(new tabbedPaneRunnable()));
				t.start();
				while (progress < progressMax) {
					try {
						
						Thread.sleep(/* random.nextInt(1000) */100);
					} catch (InterruptedException ignore) {
					}

					if(current!=null) {
						progress = current.getProgress();
					}
					
					setProgress(Math.min(progress, progressMax));
				}
				return null;
			}

			/*
			 * Executed in event dispatching thread
			 */
			@Override
			public void done() {
				progdialog.dispose();
				setProgress(0);
				Toolkit.getDefaultToolkit().beep();
				setCursor(null); // turn off the wait cursor
			}
		}

		class ProgressMonitor extends JDialog {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			Container contentPane;
			Timer timer;

			public ProgressMonitor(JFrame parent) {
				super(parent, "Cargando");
				pbar = new JProgressBar(0, 38);
				contentPane = getContentPane();
				contentPane.add(BorderLayout.CENTER, pbar);
				contentPane.add(BorderLayout.NORTH, new JLabel("Progreso..."));
				this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
			}
		}
		
		public PostresElyMainFrame() {
			super("Postres Ely Produccion");
			
			allTables = new ArrayList<ArrayList<JTable>>();
			URL imgURL = ClassLoader.getSystemResource("images/cerezitas.png");
			Image image = Toolkit.getDefaultToolkit().getImage(imgURL);

			ImageIcon planicon = new ImageIcon(image);
			
			Image img = planicon.getImage();  
			Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
			planicon = new ImageIcon(newimg);
			
			this.setIconImage(newimg);
			
			setSize(WIDTH, HEIGHT);
            addComponentListener(this);
			parent = this;
			setDefaultCloseOperation(EXIT_ON_CLOSE);
			
			imgURL = ClassLoader.getSystemResource("images/red.png");
			image = Toolkit.getDefaultToolkit().getImage(imgURL);


			redicon = new ImageIcon(image);

			img = redicon.getImage();  
			newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
			redicon = new ImageIcon(newimg);

			imgURL = ClassLoader.getSystemResource("images/green.png");
			image = Toolkit.getDefaultToolkit().getImage(imgURL);

			greenicon = new ImageIcon(image);

			img = greenicon.getImage();  
			newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
			greenicon = new ImageIcon(newimg);
			
			dialog = new JDialog(parent, "", true);

			 
			dialog.setTitle("Fecha");
			
			Container dialogContentPane = dialog.getContentPane();
			dialogContentPane.setLayout(new BorderLayout());
			//dialogContentPane.add(new JLabel("Escoja la fecha",JLabel.CENTER), BorderLayout.NORTH);
			
			JPanel datepanel = new JPanel(new GridBagLayout());
			
			date = new JDateChooser(new DateTime().now().toLocalDate().toDate());
			date.getDateEditor().setDateFormatString("yyyy/MM/dd");
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;

			
			datepanel.add(date, c);
			
			dialogContentPane.add(datepanel,BorderLayout.CENTER);
			
			JPanel buttonpanel = new JPanel(new GridBagLayout());
			
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand("Cancelar");

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;

			buttonpanel.add(cancelarbutton, c);

			JButton confirmarbutton = new JButton("OK",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand("OK");

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;

			buttonpanel.add(confirmarbutton, c);
			
			dialogContentPane.add(buttonpanel, BorderLayout.SOUTH);
			dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
			dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
			dialog.setSize(new Dimension(300, 150));
			dialog.setVisible(true);
			 
			if(ok) {
				contentPane = getContentPane();
			contentPane.setLayout(new BorderLayout());
			progdialog = new ProgressMonitor(parent);
			
			task = new Task();
			task.addPropertyChangeListener(this);
	
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {

					setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		
					task.execute();
					
					progdialog
					.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
					progdialog
					.setLocationRelativeTo(parent);
					progdialog.pack();
					progdialog.setVisible(true);
				
					contentPane.add(tabbedPane);
					contentPane.validate();
				}
			});
			
			setVisible(true);
			}
			else {
				dispose();
			}

		}
		
		public void setupTabbedPane() {
			tabbedPane = new JTabbedPane();
			tabbedPane.putClientProperty(Options.EMBEDDED_TABS_KEY, Boolean.TRUE);
			
			current = new PudinesPanel(parent,ProduccionBase.TipoBase.Vainilla,0,dia);
			current.init();
			allTables.add(current.getTable());
			
			tabbedPane.addTab("Vainilla", null, current, null);
			
			current = new PudinesPanel(parent,ProduccionBase.TipoBase.Chocolate,10,dia);
			current.init();
			allTables.add(current.getTable());


			tabbedPane.addTab("Chocolate", null, current, null);
			
			current = new PudinesPanel(parent,ProduccionBase.TipoBase.Postre,18,dia);
			current.init();
			allTables.add(current.getTable());

			
			tabbedPane.addTab("Postre", null, current, null);
			
			current = new PudinesPanel(parent,ProduccionBase.TipoBase.Pie,27,dia);
			current.init();
			allTables.add(current.getTable());

			
			tabbedPane.addTab("Pie", null, current, null);
			
			current = new PudinesPanel(parent,ProduccionBase.TipoBase.Helado,36,dia);
			current.init();
			allTables.add(current.getTable());

			
			tabbedPane.addTab("Helado", null, current, null);
			
			DespachosPanel despachos = new DespachosPanel(parent,dia,allTables);
			
			tabbedPane.addTab("Despachos", null, despachos, null);
			
			current.setProgress(Constants.MAX_PROGRESS);

			
		}
		
		public static void main(String[] args) {
			PlasticLookAndFeel.setPlasticTheme(new DesertBlue());
			   try {
			      UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
			   } catch (Exception e) {}
			new PostresElyMainFrame();

		}

		@Override
		public void componentHidden(ComponentEvent arg0) {			
		}

		@Override
		public void componentMoved(ComponentEvent arg0) {			
		}

		@Override
		public void componentResized(ComponentEvent e) {
	           int width = getWidth();
	           int height = getHeight();
	         boolean resize = false;
	           if (width < MIN_WIDTH) {
	                resize = true;
	                width = MIN_WIDTH;
	         }
	           if (height < MIN_HEIGHT) {
	                resize = true;
	                height = MIN_HEIGHT;
	           }
	         if (resize) {
	               setSize(width, height);
	         }
	        }

		@Override
		public void componentShown(ComponentEvent arg0) {			
		}

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			if ("progress" == evt.getPropertyName()) {
				int progress = (Integer) evt.getNewValue();
				pbar.setValue(progress);				
			}
			
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if(arg0.getActionCommand().equals("OK")) {
				ok = true;
				dia = new DateTime(date.getDate());
				dialog.dispose();
			}
			else if(arg0.getActionCommand().equals("Cancelar")) {
				ok = false;
				dialog.dispose();
			}
			
			
		}


}
